import React, { useState, useEffect } from "react";
import ReactEcharts from "echarts-for-react";
import { Card, Button } from "antd";

const PieChart = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = () => {
      const res = {
        status: 0,
        data: {
          dataPoints: [
            { value: 335, name: "直接访问" },
            { value: 310, name: "邮件营销" },
            { value: 234, name: "联盟广告" },
            { value: 135, name: "视频广告" },
            { value: 154, name: "搜索引擎" },
          ],
        },
      };

      if (res.status === 0) {
        setData(res.data.dataPoints);
      }
    };

    setTimeout(fetchData, 100);
  }, []);

  const getOption = (dataPoints) => ({
    title: {
      text: "饼图示例",
      subtext: "数据展示",
      left: "center",
      top: "top",
      textStyle: {
        color: "green",
        fontSize: 18,
        fontWeight: "bold",
      },
      subtextStyle: {
        color: "gray",
        fontSize: 14,
      },
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
      top: "center",
      itemGap: 10,
    },
    series: [
      {
        name: "访问来源",
        type: "pie",
        radius: "50%",
        center: ["50%", "50%"], // 确保饼图在中心
        data: dataPoints,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          formatter: "{b}: {c} ({d}%)",
        },
      },
    ],
  });

  const update = () => {
    setData(
      data.map((item) => ({
        ...item,
        value: item.value + 10,
      }))
    );
  };

  return (
    <div>
      <Card
        title={
          <Button type="primary" onClick={update}>
            更新数据
          </Button>
        }
      >
        <ReactEcharts
          option={getOption(data)}
          style={{ height: "400px", width: "100%" }}
        />
      </Card>
    </div>
  );
};

export default PieChart;
